package com.pactera.madp.cp.service.impl;

import com.pactera.madp.admin.api.entity.SysRole;
import com.pactera.madp.admin.api.feign.RemoteUserService;
import com.pactera.madp.common.core.constant.SecurityConstants;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.vo.role.RoleVo;
import com.pactera.madp.cp.api.vo.role.UserVo;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import com.pactera.madp.cp.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private IWorkEmployeeService workEmployeeService;

    @Override
    public List<RoleVo> selectAll() {
        R<List<SysRole>> allRole = remoteUserService.getAllRole();
        ArrayList<RoleVo> vos = new ArrayList<>();
        allRole.getData().forEach(f -> {
            RoleVo vo = new RoleVo();
            vo.setId(f.getRoleId());
            vo.setName(f.getRoleName());
            vos.add(vo);
        });

        return vos;
    }

    @Override
    public List<UserVo> queryUserById(Integer roleId) {
        R<List<String>> r = remoteUserService.queryUserById(roleId, SecurityConstants.FROM_IN);
        List<String> phones = r.getData();
        Integer corpId = CorpContextHolder.getCorpId();
        List<WorkEmployeeEntity> list = workEmployeeService.lambdaQuery().
                select(WorkEmployeeEntity::getId, WorkEmployeeEntity::getName).in(WorkEmployeeEntity::getMobile, phones).eq(WorkEmployeeEntity::getCorpId, corpId).list();
        ArrayList<UserVo> vos = new ArrayList<>();
        list.forEach(f -> {
            UserVo vo = new UserVo();
            BeanUtils.copyProperties(f, vo);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public String getRoleName(Integer roleId) {
        String roleName = remoteUserService.getRoleName(roleId, SecurityConstants.FROM_IN).getData();
        return roleName;
    }
}
